import axios from 'axios';
import { ElNotification } from 'element-plus';

const config = {
  baseURL: import.meta.env.VITE_BASE_ORIGIN,
  timeout: 60 * 1000, // Timeout
  withCredentials: false // Check cross-site Access-Control
};

const _axios = axios.create(config);

// 添加一个请求拦截器
_axios.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    config.headers['Authorization'] = localStorage.getItem('Authorization');
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// 添加一个响应拦截器
_axios.interceptors.response.use(
  function (response) {
    // Do something with response data
    return response.data;
  },
  function (error) {
    // Do something with response error
    if (!error.response) {
      ElNotification.error({ message: `${error.name}:${error.message}` });
    } else if (error.response.status === 401) {
      // 未在统一认证中心登录
      ElNotification.error({ message: '登录状态过期!' });

      const currentURL = window.location.href;
      const loginUrl = `${import.meta.env.VITE_BASE_ORIGIN}/v1/webapi/cas/client/dologin`;

      fetch(loginUrl, {
        method: 'POST',
        body: JSON.stringify({
          url: currentURL
        }),
        headers: {
          'Content-Type': 'application/json'
        }
      })
        .then((response) => response.json())
        .then((res) => {
          window.location.href = res.data;
        })
        .catch((err) => {
          console.log(err);
        });
    } else if (error.response.status === 403) {
      ElNotification.error({ message: '权限不足,请联系管理员!' });
    } else if (error.response.status === 404) {
      ElNotification.error({ message: '未找到您请求的资源!' });
    } else if (error.response.status === 500) {
      ElNotification.error({ message: '服务器错误⊙﹏⊙∥' });
    } else {
      const message =
        error.response.status && error.response.statusText
          ? `HTTP ERROR:(${error.response.status}:${error.response.statusText})`
          : '未知错误!';
      ElNotification.error({ message });
    }
    return Promise.reject(error);
  }
);

export default _axios;
